<template>
    <el-form :model="calendarForm" :rules="rules" ref="calendarForm" label-width="85px">
        <el-form-item label="日程内容" prop="content"><el-input v-model="calendarForm.content" placeholder="30个字符以内" maxlength="30" :disabled="dialogType === 2"></el-input></el-form-item>
        <el-form-item label="日程类型" prop="type">
            <!-- 查看的 -->
            <template v-if="dialogType === 2">
                <el-input :value="calendarCate" disabled></el-input>
            </template>
            <!-- 新建或者编辑的 -->
            <template v-else>
                <el-select v-model="calendarForm.type" placeholder="请选择日程">
                    <template v-for="item of classify">
                        <el-option :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </template>
                </el-select>
            </template>
        </el-form-item>

        <template v-if="calendarForm.type == 2">
            <!-- 账号有班级 -->
            <el-form-item v-if="class_options.length > 0" label="参与班级" prop="class_id">
                <el-checkbox-group v-model="calendarForm.class_id" :disabled="dialogType === 2">
                    <el-checkbox v-for="(item, index) in class_options" :label="item.id" :key="index">{{ item.rename }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <!-- 账号未绑定班级 -->
            <el-form-item v-else label="参与班级" required>
                <span class="no-class">(提示：您的账号未绑定班级，无法创建班级日程，请联系管理员绑定)</span>
            </el-form-item>
        </template>

        <el-form-item v-if="calendarForm.type == 3" label="参与年级" prop="grade_id">
            <el-cascader v-model="calendarForm.grade_id" :options="orgData" :props="orgDataProps" placeholder="请选择年级" :show-all-levels="false" :disabled="dialogType === 2"></el-cascader>
        </el-form-item>

        <el-form-item v-if="calendarForm.type != 1 && calendarForm.type != ''" label="参与人员" prop="role_id">
            <template>
                <el-checkbox-group v-model="calendarForm.role_id" :disabled="dialogType === 2">
                    <el-checkbox label="6">教师</el-checkbox>
                    <el-checkbox label="4">学生</el-checkbox>
                    <el-checkbox label="5">家长</el-checkbox>
                </el-checkbox-group>
            </template>
        </el-form-item>

        <el-form-item label="开始时间" prop="start_time">
            <el-date-picker v-model="calendarForm.start_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" :disabled="dialogType === 2"></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
            <el-date-picker v-model="calendarForm.end_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" :disabled="dialogType === 2"></el-date-picker>
        </el-form-item>

        <el-form-item label="重要活动" prop="is_import">
            <el-radio-group v-model="calendarForm.is_import" :disabled="dialogType === 2">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <span class="is_import_tips">(重要活动有星号标记)</span>
        </el-form-item>

        <el-form-item label="重复" prop="repeat">
            <el-select v-model="calendarForm.repeat" placeholder="请选择周期" :disabled="dialogType === 2">
                <el-option v-for="item in repeat_options" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="备注" class="textarea-item" prop="remark">
            <el-input type="textarea" :rows="6" resize="none" v-model.trim="calendarForm.remark" maxlength="140" :disabled="dialogType === 2"></el-input>
            <span class="word-sum">
                <i>{{ calendarForm.remark.length }}</i>
                /140
            </span>
        </el-form-item>

        <template v-if="dialogType === 2">
            <el-form-item label="创建人：">
                <span>{{ calendarForm.create_name }}</span>
            </el-form-item>

            <el-form-item label="创建日期：">
                <span>{{ calendarForm.create_time }}</span>
            </el-form-item>
        </template>

        <el-form-item v-if="dialogType != 2">
            <el-button v-if="dialogType == 1 || userId == createrId" type="danger" size="small" @click="delCalendar">删 除</el-button>
            <el-button size="small" @click="refresh">取 消</el-button>
            <el-button
                type="primary"
                size="small"
                v-loading.fullscreen="submitLoading"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                element-loading-text="正在提交..."
                @click="submitForm('calendarForm')"
            >
                确定
            </el-button>                
        </el-form-item>
    </el-form>
</template>

<script>
export default {
    data(){
        return{
            userId: this.$store.getters.userInfo.id,
            createrId:null,
            dialogType:0,//0新建，1编辑，2查看
            orgParam: {
				level_string: '<4',
				data_type: 'manage_tree',
				status: 1
            },
            orgData: [],
			orgDataProps: {
				value: 'id',
				label: 'name',
				children: 'children'
            },
            class_options: [],
            repeat_options: [
				{
					value: 0,
					label: '不重复'
				},
				{
					value: 1,
					label: '每天'
				},
				{
					value: 2,
					label: '每周'
				},
				{
					value: 3,
					label: '每月'
				}
			],
            calendarForm: {
				id: null,
				content: '',
				type: 1,
				start_time: '',
				end_time: '',
				is_import: 0,
				repeat: 0,
				remark: '',
				create_id: this.$store.getters.userInfo.id,
				class_id: [],
				grade_id: [],
				role_id: [], //参与人员id
				term_id: [] //学期id
            },
            rules: {
				content: [
					{
						required: true,
						message: '请输入日程名称',
						trigger: 'blur'
					}
				],
				type: [
					{
						required: true,
						message: '请选日程类型',
						trigger: 'change'
					}
				],
				start_time: [
					{
						required: true,
                        validator: this.validateDateStart,
						trigger: 'change'
					}
				],
				end_time: [
					{
						required: true,
                        validator: this.validateDateEnd,
						trigger: 'change'
                    }
				],
				class_id: [
					{
						type: 'array',
						required: true,
						message: '请选择班',
						trigger: 'change'
					}
				],
				grade_id: [
					{
						type: 'array',
						required: true,
						message: '请选择年级',
						trigger: 'change'
					}
				],
				role_id: [
					{
						type: 'array',
						required: true,
						message: '请至少选择一个参与人',
						trigger: 'change'
					}
				],
				repeat: [{ required: true, message: '请选周期', trigger: 'change' }]
			},
            submitLoading: false,

        }
    },
    created(){
        if(this.$store.getters.isMulti){ //年级
            this.getOrgData1();
        }else{
            this.getOrgData();
        }
        this.getUserClass();
    },
    computed: {
        // 获取日程类型
        classify(){
            // 用户的身份:1、2:超级管理员；3前台管理员；4学生；5家长，6教师
            let role = this.$store.getters.userInfo.rolebaseid;
            let arr = [
                {
                    value: 1,
                    label: '个人日程',
                    role: [1, 2, 3, 4, 5, 6]
                },
                {
                    value: 2,
                    label: '班级日程',
                    role: [1, 2, 3, 6]
                },
                {
                    value: 3,
                    label: '年级日程',
                    role: [1, 2, 3, 6]
                },
                {
                    value: 4,
                    label: '校级日程',
                    role: [1, 2, 3]
                }
            ]
            arr = arr.filter(x =>{
               return role.some(y => {return x.role.includes(y)})
            })
            return arr;
        },
        calendarCate(){
            return this.$parent.$parent.tableTips[this.calendarForm.type -1];
        }
        
    },
    methods: {
        validateDateStart(rule, value, callback) {
            if (value === '') {
                return callback(new Error('请选择开始时间'));
            }else{
                const flag = this.calendarForm.end_time && new Date(this.calendarForm.start_time).getTime() >= new Date(this.calendarForm.end_time).getTime();
                if (flag){
                    return callback(new Error('开始时间不能 大于 或 等于 结束时间'));
                } else {
                    callback()
                }
            }
        },  
        validateDateEnd(rule, value, callback) {
            if (value === '') {
                return callback(new Error('请选择结束时间'));
            }else{
                const flag = this.calendarForm.start_time && new Date(this.calendarForm.start_time).getTime() >= new Date(this.calendarForm.end_time).getTime();
                if (flag){
                    return callback(new Error('结束时间不能 小于 或 等于 开始时间'));
                } else {
                    callback()
                }
            }

        },     
        // 单机版本-获取年级
		getOrgData() {
			let success = data => {
				// 后台返回的多层嵌套数据，第3层的children键值对值为[]时，element的cascader级联选择器在页面显示4级为空白，所以要把第3层的children键值对的值设为undefined
				this.orgData = this.getTreeData(data.data);
			};
			this.$ajax.get('api/org/org', {
				params: this.orgParam,
				func: { success: success }
			});
        },
        // 递归遍历将多层嵌套数组里最里的空children数组的值改为undefined
		getTreeData(data) {
			// 循环遍历json数据
			for (var i = 0; i < data.length; i++) {
				if (data[i].children.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i].children = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i].children);
				}
			}
			return data;
		},
		// 多级版本-获取年级
        getOrgData1() {
			let success = data => {
                this.orgData = data.data;
			};
			this.$ajax.get('api/newlevel/levelorg_list', {
				params: {
                    type:2 
                },
				func: { success: success }
			});
        },
        //获取用户的班级：
		getUserClass() {
			let success = res => {
				this.class_options = res.data;
			};
			this.$ajax({
				url: 'api/org/class_userid',
				method: 'get',
				params: {
					user_id: this.$store.getters.userInfo.id
				},
				func: { success: success }
			});
		},
        //弹窗关闭事件：（新建和编辑共用一个含form表单的弹窗，这里做清空处理）
		closeDialog() {
			// this.calendarForm = deep_clone(this.defaultCalendarForm); //清空数据
			// this.$refs.calendarForm.clearValidate(); //清除所有的必选验证
        },
        //确定按钮：
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
                    if(this.calendarForm.type === 2 && this.class_options.length === 0){//
                        this.$message.error('您的账号未绑定班级，无法创建班级日程，请联系管理员绑定');
                        return;
                    }
					if (this.dialogType == 0) {
						this.save('post');
					} else if (this.dialogType == 1) {
						this.save('put');
					}
				} else {
					console.log('error submit!!');
					return false;
				}
			});
        },
        // 提交日程数据
        save(type) {
			this.submitLoading = true;
			let success = res => {
				this.submitLoading = false;
				if (type === 'post') {
					this.$message.success('新增成功');
				} else if (type === 'put') {
					this.$message.success('编辑成功');
                }
                this.refresh();
			};
			let fail = res => {
				this.$message.error(res.msg);
				this.submitLoading = false;
			};
			this.$ajax({
				url: 'api/schedule/schedule',
				method: type,
				data: this.calendarForm,
				func: { success: success, fail: fail }
			});
        },
        // 删除日程：
		delCalendar() {
			let yes = data => {
				let success = res => {
					this.$message.success('删除成功');
                    this.refresh();
				};
				this.$ajax({
					url: 'api/schedule/schedule',
					method: 'delete',
					params: {
						id: this.calendarForm.id
					},
					func: { success: success }
				});
			};
			let cancel = data => {};
			this.e_confirm({
				yes: yes,
				cancel: cancel,
				txt: '确定删除此个日程吗？'
			});
        },
        
        refresh(){
            this.$parent.$parent.getdata();//因为当前组件是嵌套在calendar.vue组件的一个el-dialog组件里的，所以嵌套了2层，就写俩个$parent才能调用到
        }
    }
}
</script>

<style lang="scss">
    .el-dialog {
        .el-dialog__header {
            background-color: #409eff;
            padding: 10px 20px;
        }
        .el-dialog__body {
            padding: 30px 30px 30px 20px;
        }
        .el-dialog__title {
            color: #fff;
        }
        .el-dialog__headerbtn {
            top: 1px;
            right: 10px;
            padding: 10px;
            .el-dialog__close {
                font-size: 20px;
                color: #fff;
            }
        }
        .el-select {
            width: 100%;
        }
        .el-date-editor.el-input,
        .el-date-editor.el-input__inner {
            width: 100%;
        }
        .is_import_tips {
            color: #999;
            margin-left: 20px;
        }
        .textarea-item {
            position: relative;
            .word-sum {
                position: absolute;
                bottom: 0px;
                right: 20px;
            }
        }
        .no-class{
            color: #f56c6c;
        }
    }

</style>